import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_pickers/pickers.dart';
import 'package:flutter_pickers/style/default_style.dart';
import 'package:flutter_yishop/config/Config.dart';
import 'package:flutter_yishop/config/EventBus.dart';
import 'package:flutter_yishop/services/SignService.dart';
import 'package:flutter_yishop/services/UserService.dart';
import 'package:flutter_yishop/utils/screen/ScreenAdapter.dart';
import 'package:flutter_yishop/utils/toast_util.dart';
import 'package:flutter_yishop/widget/JdButton.dart';
import 'package:flutter_yishop/widget/JdText.dart';

class AddressEditPage extends StatefulWidget{

  Map arguments;
  AddressEditPage({Key key,this.arguments}):super(key: key);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _AddressEditPageState();
  }

}

class _AddressEditPageState extends State<AddressEditPage>{

  String area = "";
  String address = "";
  String province = "";//省
  String city="";//市
  String county="";//区
  String detailsAddress = "";//详细地址
  TextEditingController nameController = TextEditingController();
  TextEditingController phoneController = TextEditingController();
  TextEditingController detailsAddressController = TextEditingController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    nameController.text = widget.arguments["name"];
    phoneController.text = widget.arguments["phone"];
    // addressController.text = widget.arguments["address"];
    // print('地址：${widget.arguments["address"]}');
    getAddress();
  }

  void getAddress() {
    String allAddress =   widget.arguments["address"];
    print('allAddress:$allAddress');
    try{
      province = allAddress.substring(allAddress.indexOf("p:")+2,allAddress.indexOf("c:"));
      city = allAddress.substring(allAddress.indexOf("c:")+2,allAddress.indexOf("t:"));
      county = allAddress.substring(allAddress.indexOf("t:")+2,allAddress.indexOf("a:"));
      detailsAddress = allAddress.substring(allAddress.indexOf("a:")+2,allAddress.length);
      print('p:$province c:$city t:$county a:$detailsAddress');
      area = "$province$city$county";
      detailsAddressController.text = detailsAddress;
      this.address =  "p:${province == "全部" ? "" : province}c:${city == "全部" ? "" : city}t:${county == "全部" ? "" : county}a:$detailsAddress";
    }catch(e){

    }

  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    ScreenAdapter.init(context);
    return Scaffold(
      appBar: AppBar(
        title: Text("修改收货地址"),
      ),
      body: Container(
        padding: EdgeInsets.all(10),
        child: ListView(
          children: <Widget>[
            SizedBox(height: 20),
            JdText(
              controller: nameController,
              text: "收货人姓名",
              onChanged: (value) {
               nameController.text = value;
              },
            ),
            SizedBox(height: 10),
            JdText(
              controller: phoneController,
              text: "收货人电话",
              onChanged: (value) {
                phoneController.text = value;
              },
            ),
            SizedBox(height: 10),
            Container(
              padding: EdgeInsets.only(left: 5),
              height: ScreenAdapter.height(68),
              decoration: BoxDecoration(
                  border: Border(
                      bottom: BorderSide(width: 1, color: Colors.black12))),
              child: InkWell(
                child: Row(
                  children: <Widget>[
                    Icon(Icons.add_location),
                    this.area.length > 0
                        ? Text('${this.area}',
                        style: TextStyle(color: Colors.black54))
                        : Text('省/市/区', style: TextStyle(color: Colors.black54))
                  ],
                ),
                onTap: () async {
                  Pickers.showAddressPicker(context,
                      initProvince: province,
                      initCity: city,
                      initTown: county,
                      pickerStyle: RaisedPickerStyle(), onConfirm: (p, c, t) {
                        setState(() {
                          this.area =
                          "${p == "全部" ? "" : p}${c == "全部" ? "" : c}${t == "全部" ? "" : t}";
                          province = (p == "全部" ? "" : p);
                          city = (c == "全部" ? "" : c);
                          county = (t == "全部" ? "" : t);
                          // this.address =  "p:${p == "全部" ? "" : p}c:${c == "全部" ? "" : c}t:${t == "全部" ? "" : t}";
                        });
                      });
                },
              ),
            ),
            SizedBox(height: 10),
            JdText(
              controller: detailsAddressController,
              text: "详细地址",
              maxLines: 4,
              height: 200,
              onChanged: (value) {
                detailsAddress = value;

              },
            ),
            SizedBox(height: 10),
            SizedBox(height: 40),
            JdButton(
              text: "修改",
              color: Colors.red,
              cb: ()  {
                // Navigator.pop(context);
                _changeAddressRequest();
              },
            )
          ],
        ),
      ),
    );
  }

  _changeAddressRequest()async{
    this.address =  "p:${province}c:${city}t:${county}a:$detailsAddress";
    List userinfo=await UserService.getUserInfo();
    var tempJson = {
      "uid":userinfo[0]["_id"],
      "id":widget.arguments["id"],
      "name": nameController.text,
      "phone":phoneController.text,
      "address":address,
      "salt":userinfo[0]["salt"]
    };

    var sign = SignService.getSign(tempJson);
    var api = "${Config.url}api/editAddress";
    var result = await Dio().post(api, data: {
      "uid":userinfo[0]["_id"],
      "id":widget.arguments["id"],
      "name": nameController.text,
      "phone":phoneController.text,
      "address":address,
      "sign":sign
    });
    if(result.data["success"]){
      Navigator.pop(context);
    }else{
      ToastUtil.showToasts(result.data["message"]);
    }
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    eventBus.fire(new AddressEvent("修改成功"));
  }

}



